<?php

namespace App\Kuafu\Export\Controller\B;

use App\Exceptions\BaseException;
use App\Kuafu\Base\Controller\BaseController;
use App\Kuafu\Base\Enum\BaseCodeEnum;
use App\Kuafu\Export\Model\ExportDownloadModel;
use App\Kuafu\Export\Service\ExportDownloadService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use function auth;

class ExportDownloadsController extends BaseController
{
    public function lists(Request $request): JsonResponse
    {
        $pageSize = $request->get('pageSize', 20);
        $pageNum  = $request->get('pageNum', 1);

        $userId = auth('api')->user()->id ?? 0;

        $client = ExportDownloadModel::CLIENT_TYPE_WEB;
        return $this->success(ExportDownloadService::lists($client, $userId, $pageSize, $pageNum));
    }

    public function delete(Request $request, int $id): JsonResponse
    {
        (new ExportDownloadModel())->del($id);

        return $this->success();
    }

    /**
     * 远程导出-创建
     * @param Request $request
     * @return JsonResponse
     * @throws BaseException
     */
    public function remoteExportAdd(Request $request): JsonResponse
    {
        $fileType     = (int)$request->get('fileType', 0);
        $name         = (string)$request->get('name', '');
        $params       = $request->get('params', []);
        $createdByUid = (int)$request->get('createdByUid', 0);
        if (!in_array($fileType,
            [
                ExportDownloadModel::FILE_TYPE_WEB_TIGER_WORK_ORDER,
                ExportDownloadModel::FILE_TYPE_WEB_TIGER_APPRAISE,
                ExportDownloadModel::FILE_TYPE_WEB_ALBUM_RESOURCE,
                ExportDownloadModel::FILE_TYPE_WEB_ARTICLE_HOLISTIC_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_ARTICLE_SINGLE_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_CATEGORY_SINGLE_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_CATEGORY_HOLISTIC_ANALYSIS,
                ExportDownloadModel::FILE_TYPE_WEB_SHOP_ORDER_ACTIVITY_SHOP_LIST,
                ExportDownloadModel::FILE_TYPE_WEB_SHOP_ACTIVITY_LIST,
                ExportDownloadModel::FILE_TYPE_WEB_SHOP_ACTIVITY_SHOP_LIST,
                ExportDownloadModel::TYPE_SHOP_LICENSE_RECORDS_LIST,
            ]) && $fileType < ExportDownloadModel::FILE_TYPE_TIGER_MIN) {
            throw new BaseException(BaseCodeEnum::ERR_400000);
        }
        $client = ExportDownloadModel::CLIENT_TYPE_WEB;
        return $this->success(ExportDownloadService::remoteExportAdd($client, $fileType, $params, $name, $createdByUid));
    }

    /**
     * 远程导出-完成
     * @param Request $request
     * @return JsonResponse
     */
    public function remoteExportFinish(Request $request): JsonResponse
    {
        $id   = (int)$request->get('id', 0);
        $path = (string)$request->get('path', '');

        return $this->success(ExportDownloadService::remoteExportFinish($id, $path));
    }
}
